import os
from django.shortcuts import render
from common.models import Goods,Types
from datetime import datetime
import time
from PIL import Image
from django.core.paginator import Paginator

# Create your views here.
def index(request,page):
    '''浏览商品列表'''
    goodslist=Goods.objects.all()
    # 获取商品类别名称
    for goods in goodslist:
        typeOBJ=Types.objects.get(id=goods.typeid)
        goods.typename=typeOBJ.name
    # 分页信息
    pagelist=[]#页码
    p = Paginator(goodslist,5)
    if page is None or page == '':
        page = 1
    page = int(page)
    curGoodsList = p.page(page)
    pagelist = p.page_range
    context={"goodslist":curGoodsList,"pagelist":pagelist}
    return render(request,'admin/goods/index.html',context)

def add(request):
    '''加载添加商品页面'''
    # 获取类别列表
    typeslist=Types.objects.extra(select={'_has':'concat(path,id)'}).order_by("_has")
    context={"typeslist":typeslist}
    return render(request,'admin/goods/add.html',context)

# 上传图片
def uploadPics(picfile):
    filename = str(time.time()) + "." + picfile.name.split(".").pop()
    destination = open("./static/admin/upload/" + filename, "wb+")
    for chunk in picfile.chunks():
        destination.write(chunk)
    destination.close()
    # 图片缩放
    # 大图
    img_thumb = Image.open("./static/admin/upload/" + filename)
    img_thumb.thumbnail((375,375))
    img_thumb.save("./static/admin/upload/" + filename, None)
    # 中图
    img_thumb.thumbnail((220, 220))
    img_thumb.save("./static/admin/upload/m_" + filename, None)
    # 小图
    img_thumb.thumbnail((75,75))
    img_thumb.save("./static/admin/upload/s_"+filename,None)
    return filename

def insert(request):
    '''执行添加'''
    ispicupload=False # 新图片上传成功
    try:
        # 图片上传
        picfile = request.FILES.get("pic", "")
        if not picfile:
            context = {"message": "没有上传文件信息！"}
        else:
            filename = uploadPics(picfile)  # 上传图片
            ispicupload=True
        # 商品信息
        gobj=Goods()
        gobj.goods = request.POST['goods']
        gobj.typeid = request.POST['typeid']
        gobj.company = request.POST['company']
        gobj.price = request.POST['price']
        gobj.store = request.POST['store']
        gobj.content = request.POST['content']
        gobj.picname = filename
        gobj.state = 1
        gobj.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        gobj.save()
        context = {"info": "添加成功！"}
    except Exception as err:
        context={"info":"添加失败！"+str(err)}
        # 删除新图片
        if ispicupload:
            os.remove("./static/admin/upload/" + filename)
            os.remove("./static/admin/upload/m_" + filename)
            os.remove("./static/admin/upload/s_" + filename)
    return render(request,'admin/info.html',context)

def delete(request,gid):
    '''删除商品'''
    try:
        gobj=Goods.objects.get(id=gid)
        # 删除图片
        os.remove("./static/admin/upload/" + gobj.picname)
        os.remove("./static/admin/upload/m_" + gobj.picname)
        os.remove("./static/admin/upload/s_" + gobj.picname)
        gobj.delete()
        context = {"info": "删除成功！"}
    except Exception as err:
        context={"info":"删除失败！"}
    return render(request,'admin/info.html',context)

def edit(request,gid):
    '''加载编辑商品信息'''
    try:
        typeslist = Types.objects.extra(select={'_has': 'concat(path,id)'}).order_by("_has")
        gobj=Goods.objects.get(id=gid)
        context={"typeslist": typeslist,'goods':gobj}
        return render(request, 'admin/goods/edit.html',context)
    except Exception as err:
        context={"info":"查询商品信息失败！"}
    return render(request,'admin/info.html',context)

def update(request,gid):
    '''执行商品编辑'''
    ispicupload=False # 新图片上传成功
    try:

        newpicfile = request.FILES.get("pic", "")
        oldpicname=request.POST["oldpicname"]
        picname=""#图片名称
        if not newpicfile:
            # 如果没有上传新图片，使用原图片地址
            picname = oldpicname
        else:# 上传了新图片
            picname = uploadPics(newpicfile)  # 上传图片
            ispicupload=True
        # 商品信息
        gobj = Goods.objects.get(id=gid)
        gobj.goods = request.POST['goods']
        gobj.typeid = request.POST['typeid']
        gobj.company = request.POST['company']
        gobj.price = request.POST['price']
        gobj.store = request.POST['store']
        gobj.content = request.POST['content']
        gobj.picname = picname
        gobj.state = request.POST['state']
        gobj.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        gobj.save()
        context = {"info": "修改成功！"}
        # 删除旧图片
        if ispicupload:
            os.remove("./static/admin/upload/" + oldpicname)
            os.remove("./static/admin/upload/m_" + oldpicname)
            os.remove("./static/admin/upload/s_" + oldpicname)
    except Exception as err:
        print(err)
        context={"info":"修改失败！"}
        # 删除新图片
        if ispicupload:
            os.remove("./static/admin/upload/" + picname)
            os.remove("./static/admin/upload/m_" + picname)
            os.remove("./static/admin/upload/s_" + picname)
    return render(request,'admin/info.html',context)